const { axios } = require('../../utils/http')
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify.js'
import jwt from '../../miniprogram_npm/jwt-decode/index'
import { md5 } from '../../utils/util'
Page({
  data: {
    username: '',
    password: '',
    active: 4
  },
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        active: 4
      })
    }
  },
  forgetPassword() {
    wx.navigateTo({
      url: '/pages/forget/forget'
    })
  },
  goLoginForWX() {
    wx.getUserProfile({
      desc: '登陆', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: ({ userInfo }) => {
        axios
          .post('/user/wxLogin', {
            username: userInfo.nickName,
            password: userInfo.nickName,
            avatar: userInfo.avatarUrl
          })
          .then(res => {
            if (res.data.error === 0) {
              Notify('登录失败')
              return
            } else {
              const userInfo = jwt(res.data.data)
              console.log(userInfo)
              wx.setStorageSync('isLogin', true)
              wx.setStorageSync('userInfo', userInfo)
              wx.setStorageSync('token', res.data.data)
              wx.navigateBack()
            }
          })
      }
    })
  },
  goLogin() {
    const { username, password } = this.data
    if (!username || !password) {
      Notify({
        message: '请输入用户名或密码'
      })
      return
    }
    const newPassword = md5(password)
    axios
      .post('/user/login', {
        username,
        password: newPassword
      })
      .then(res => {
        console.log(res)
        if (res.data.error === 0) {
          Notify('用户名或密码错误')
          return
        } else {
          const userInfo = jwt(res.data.data)
          wx.setStorageSync('isLogin', true)
          wx.setStorageSync('userInfo', userInfo)
          wx.setStorageSync('token', res.data.data)
          wx.navigateBack()
        }
      })
  }
})
